import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const UcodeSchema = new mongoose.Schema({
    uCode: String,
    captchaText: String,
});

UcodeSchema.methods.saveUcode = function (ucode, cb) {
    this.model('ucode').insertMany([ucode], cb);
};

UcodeSchema.methods.getUcodes = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const ucodeModel = this.model('ucode');
    ucodeModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        ucodeModel.find(leftQuery, { passwd: 0 }).skip((current - 1) * pageSize).limit(pageSize).exec((err, ucodes) => cb(err, ucodes, count, hasMore));
    });
};

UcodeSchema.methods.getAllUcodes = function (query, cb) {
    this.model('ucode').find(query, { name: 1, _id: 0 }, cb);
};

UcodeSchema.methods.getUcode = function (query, cb) {
    this.model('ucode').findOne(query, cb);
};

UcodeSchema.methods.updateUcode = function (ucode, cb) {
    const _id = ucode._id;
    delete ucode._id;
    this.model('ucode').findOneAndUpdate({ _id }, { $set: ucode }, cb);
};

UcodeSchema.methods.removeUcodes = function (ucodeIds, cb) {
    this.model('ucode').remove({ _id: { $in: ucodeIds } }, cb);
};

export default db.model('ucode', UcodeSchema);